#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <stdlib.h>
#include <sqlite3.h>
#include "door.h"
#include "doorinfo.h"
#include "portvictoria.h"

extern struct playerdata_t *player;

void display_file(char *filename) {
	FILE *fptr;
	char c;
	
	fptr = fopen(filename, "r");
	if (fptr) {
		c = fgetc(fptr);
		while (!feof(fptr)) {
			drprintf("%c", c);
			c = fgetc(fptr);
		}
		fclose(fptr);
		
		drprintf("\r\nPress ENTER to continue\r\n");
		c = drgetc();
		while (c != '\n' && c != '\r') {
			usleep(100);
			c = drgetc();
		}
	}
}

void twoup(void) {
	int wager;
	int coin1;
	int coin2;
	int done = 0;
	char c;
	
	srand(time(NULL));
	
	drprintf("How much do you wager? (You have %d, Type 0 to back out) : ", player->dollars);
	wager = read_int();
	
	if (wager == 0)
		return;
	
	if (wager > player->dollars) {
		drprintf("You can't afford that!\r\n");
		return;
	}
	
	do {
		drprintf("\r\nTo flip the coins, press ENTER...\r\n");
		c = drgetc();
		while (c != '\n' && c != '\r') {
			usleep(100);
			c = drgetc();
		}
		
		coin1 = rand() % 2;
		coin2 = rand() % 2;
		
		if (coin1 != coin2) {
			drprintf("You flipped a %s and a %s! Flip again!\r\n", (coin1 == 1 ? "Heads" : "Tails"), (coin2 == 1 ? "Heads" : "Tails"));
		} else {
			if (coin1 == 0) {
				drprintf("Two tails. You lose.\r\n");
				player->dollars -= wager;
				done = 1;
			} else if (coin1 == 1) {
				drprintf("Two heads! You Win!\r\n");
				player->dollars += wager;
				done = 1;
			} else {
				drprintf("Something strange happened... coin1 = %d and coin2 = %d\r\n", coin1, coin2);
			}
		}
	} while(!done);
	
	drprintf("\r\nGame over, Press ENTER...\r\n");
	c = drgetc();
	while (c != '\n' && c != '\r') {
		usleep(100);
		c = drgetc();
	}
		
}

int tavern(void) {
	FILE *fptr;
	char c;
	
	while (1) {
		fptr = fopen("tavern_header.ans", "r");
		if (fptr) {
			c = fgetc(fptr);
			while (!feof(fptr)) {
				drprintf("%c", c);
				c = fgetc(fptr);
			}
			fclose(fptr);
		}
		
		drprintf("\r\n\e[1;33mThe tavern is just like any other tavern.\r\n\r\n");
		drprintf("        \e[1;37m(\e[1;33mN\e[1;37m) Read a copy of the Seafarer's Daily\r\n");
		drprintf("        \e[1;37m(\e[1;33mT\e[1;37m) Play a game of two-up.\r\n");
		drprintf("        \e[1;37m(\e[1;33mS\e[1;37m) Find out what the captains of the realm are worth\r\n");
		drprintf("\r\n        \e[1;37m(\e[1;33mR\e[1;37m) Return to the docks\r\n");
		drprintf("        \e[1;37m(\e[1;31mQ\e[1;37m) Quit to BBS\e[0m\r\n");
	
		c = drgetc();
	
		while (c == -1)  {
			usleep(100);
			c = drgetc();
		}
	
		switch (tolower(c)) {
			case 'n':
				display_file("todays_news.ans");
				break;
			case 't':
				twoup();
				break;
			case 's':
				display_file("scores.ans");
				break;
			case 'r':
				return 1;
			case 'q':
				return 0;
		}
	}
}
